/*
 * FrmConsultaFatura.java
 *
 * Created on November 15, 2009, 9:54 PM
 */

package br.com.pangalacteos.apresentacao;

import br.com.pangalacteos.dao.HibernateDAO;
import br.com.pangalacteos.modelo.DBField;
import br.com.pangalacteos.modelo.Fatura;
import br.com.pangalacteos.util.Mapeator;
import br.com.pangalacteos.util.Parser;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author  Leandro Del Sole
 */
public class FrmConsultaFatura extends javax.swing.JPanel {

    List<Fatura> faturas;
    
    /** Creates new form FrmConsultaFatura */
    public FrmConsultaFatura() {
        initComponents();
        faturas = new ArrayList<Fatura>();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        txtProcurarPor = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        cmbCampo = new javax.swing.JComboBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblResultado = new javax.swing.JTable();
        btnCancelar = new javax.swing.JButton();
        btnAlterar = new javax.swing.JButton();
        btnProcurar = new javax.swing.JButton();

        jLabel1.setText("Procurar por:");

        jLabel2.setText("em:");

        cmbCampo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Identificação", "Fornecedor", "Data Fatura", "Data Vencimento", "Valor Desconto", "Fim Desconto", "Valor Montante", "Referencia", "Descrição", "Duplicata", "Nota Fiscal", "Série Nota Fiscal", "Data Pagamento", "Status" }));

        tblResultado.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Id", "Fornecedor", "Montante", "Vencimento"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(tblResultado);

        btnCancelar.setText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        btnAlterar.setText("Alterar");
        btnAlterar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAlterarActionPerformed(evt);
            }
        });

        btnProcurar.setText("Procurar");
        btnProcurar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnProcurarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(cmbCampo, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(txtProcurarPor, javax.swing.GroupLayout.DEFAULT_SIZE, 102, Short.MAX_VALUE)))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 375, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(btnProcurar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnAlterar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnCancelar)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtProcurarPor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(cmbCampo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 275, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnAlterar)
                    .addComponent(btnCancelar)
                    .addComponent(btnProcurar))
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

private void btnProcurarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnProcurarActionPerformed
    HibernateDAO<Fatura> faturaDAO = new HibernateDAO<Fatura>();
    try{
        Map<Object, DBField> comboToFatura = Mapeator.mapeiaComboBD(cmbCampo, Fatura.class);
        System.out.println("comboToFatura: " + comboToFatura);
        faturas = faturaDAO.findByField(
                Fatura.class, comboToFatura.get(cmbCampo.getSelectedItem()), 
                Parser.descobreTipo(txtProcurarPor.getText(), comboToFatura.get(cmbCampo.getSelectedItem())));
        DefaultTableModel modelo = (DefaultTableModel)tblResultado.getModel();
        modelo.setRowCount(0);
        System.out.println("Resultado: " + faturas);
        
        Iterator<Fatura> it = faturas.iterator();
        
        while(it.hasNext()){
            Fatura corrente = it.next();
            modelo.addRow(new Object[]{"", "", "", ""});
            int ultimaLinha = tblResultado.getRowCount() - 1;
            tblResultado.setValueAt(corrente.getCdfatura(), ultimaLinha, 0);
            tblResultado.setValueAt(corrente.getCdfornecedor().getNmfornecedor(), ultimaLinha, 1);
            tblResultado.setValueAt(corrente.getVlmontante(), ultimaLinha, 2);
            tblResultado.setValueAt(corrente.getDtvencimento(), ultimaLinha, 3);
        }
    } catch (ClassCastException ex){
            JOptionPane.showMessageDialog(null, "O tipo do dado buscado não condiz " +
                    " ao conteúdo buscado.\n" +
                    "Exceção: " + ex, "Erro interno",
                    JOptionPane.ERROR_MESSAGE);
            ex.printStackTrace(); 
    } catch (Exception ex){
            JOptionPane.showMessageDialog(null, "Ocorreu um erro durante a busca," +
                    " por favor relate este erro ao administrador da rede.\n" +
                    "Exceção: " + ex, "Erro interno",
                    JOptionPane.ERROR_MESSAGE);
            ex.printStackTrace();
    }
}//GEN-LAST:event_btnProcurarActionPerformed

private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
    FrmPrincipal.fecharAba(this, false);
}//GEN-LAST:event_btnCancelarActionPerformed

private void btnAlterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAlterarActionPerformed
    FrmPrincipal.getInstance().abreAba(
            new FrmFatura(faturas.get(tblResultado.getSelectedRow())), 
            "Alt. Fatura");
}//GEN-LAST:event_btnAlterarActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAlterar;
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnProcurar;
    private javax.swing.JComboBox cmbCampo;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tblResultado;
    private javax.swing.JTextField txtProcurarPor;
    // End of variables declaration//GEN-END:variables
    
}
